import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import {
  queryBuyersPage,
  createBuyer,
  updateBuyer,
  deleteBuyer,
  getBuyer,
  queryBuyers,
  updateRule,
  getBusinessParamsByCode,
} from './service';
import { TableListData } from './data.d';
import Constants from '../tradersManagement/utils/Constants';
const R = require('ramda');
const productAddTempIdPrefix = 'productAddTempIdPrefix_';
export interface StateType {
  data: TableListData;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state:{
    page: {},
    list: [],
    dataSource: {},
    type: [],
    status: [],
    buyerList:{},
    buyersList:{},
    StateType
  },
  effects: {
    fetch: Effect;
    add: Effect;
    remove: Effect;
    update: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'tradersManagement',

  state: {
    list: [],
    pagination: {},
    // productList: [], //产品列表
    // productPage: {}, //产品列表分页
    bizParams: {}, // 业务参数缓存
    // currencys: [], // 币种列表
    // ports: [], //报关口岸列表
    // privateCstList: [], //经营单位
    buyerList: {}, //境外买家
    buyersList:{},
    // supplygoodList: [], //境内货源地,
    // drawersList: [], //开票人
    // order: {}, //订单详情
    // orderTgApproval: {}, //订单通关信息
    // orderProductDetails: [], //订单产品
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      payload.type = 1;
      payload.status = 1;
      const response = yield call(queryBuyersPage, payload);
      if (response.resultCode === 'ok') {
        if (!R.isEmpty(response.content) && !R.isNil(response.content)) {
          const { page, list ,} = response.content;
          yield put({
            type: 'refreshState',
            payload: {
              list,
                pagination: { current: page.page, total: page.totalRow, pageSize: page.size },
            },
          });
        } else {
          let page = Constants.DEFAULT_PAGE;
          yield put({
            type: 'refreshState',
            payload: {
              list: [],
              pagination: { current: page.page, total: page.totalRow, pageSize: page.size },
            },
          });
        }
      }
    },

    /**
     * 新增境外贸易商
     * @param {any} payload
     * @param {any} call
     * @param {any} put
     * @param {any} select
     */
    *createBuyer({ payload }, { call, put, select }) {

      const dataSource = payload.dataSource;
      let orderProductDetails = [];
      dataSource.orderProductDetails = orderProductDetails;

      const response = yield call(createBuyer, { ...dataSource });
      if (response.resultCode === 'ok') {
        message.info('境外贸易商新增成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        message.error(response.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },

    /**
     * 更新境外贸易商
     * @param {any} payload
     * @param {any} call
     * @param {any} put
     * @param {any} select
     */
    *updateBuyer({ payload }, { call, put, select }) {
      const dataSource = payload.dataSource;
      let orderProductDetails = [];
      dataSource.orderProductDetails = orderProductDetails;
      const response = yield call(updateBuyer, { ...dataSource });
      if (response.resultCode === 'ok') {
        message.info('境外贸易商修改成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        message.error(response.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },


    /**
     * 删除境外贸易商
     * @param {any} payload
     * @param {any} callback
     * @param {any} call
     * @param {any} put
     */
      *deleteBuyer({ payload, callback }, { call, put }) {
      const response = yield call(deleteBuyer, { id: payload.id });
      if (response.resultCode === 'ok') {
        // message.info('删除境外贸易商成功!');
        if (callback) callback(response);
      }
    },


    /**
     * 根据ID获取单个境外贸易商
     * @param {any} payload
     * @param {any} call
     * @param {any} put
     * @param {any} select
     */
    *getBuyer({ payload }, { call, put, select }) {
      const response = yield call(getBuyer, { id: payload.id });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            buyerList: response.content,
            orderProductDetails: response.content.orderProductDetails,
          },
        });
      } else {
        message.error(response.errMessage);
      }
    },


    /**
     * 获取业务参数集合
     *
     * @param call
     * @param put
     * @param select
     */
      *getBusinessParamsByCode({ sprCode }, { call, put, select }) {
      const sessionSprCode = sessionStorage.getItem(Constants.PARAMPREFIX + sprCode);
      if (R.isNil(sessionSprCode)) {
        const response = yield call(getBusinessParamsByCode, { sprCode });
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PARAMPREFIX + sprCode, JSON.stringify(response.content));
          yield put({
            type: 'setBizParams',
            payload: {
              sprCode,
              buyersList: response.content,
            },
          });
        }
      } else {
        yield put({ type: 'setBizParams', payload: { sprCode, list: JSON.parse(sessionSprCode) } });
      }
    },


    /**
     * 查询境外买家
     *
     * @param call
     * @param put
     */
    *queryBuyers({ payload }, { call, put }) {
      const response = yield call(queryBuyers, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            list: response.content,
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { buyerList: [] } });
      }
    },







    *add({ payload, callback }, { call, put }) {
      const response = yield call(addRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    /**
     * 设置业务参数
     *
     * @param state
     * @param payload
     */
    setBizParams(state, { payload }) {
      let newState = state.bizParams;
      if (payload.sprCode != undefined) {
        newState[payload.sprCode] = payload.list;
      }
      return { ...state, bizParams: newState };
    },

    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
